

#include "qmaps.h"
#include <QFile>
#include <QDebug>
#include <QApplication>
#include <QVBoxLayout>
#include <QAbstractItemModel>

#include <devicemodel.hpp>
#include <qlogger.hpp>
namespace{
QLogger* l = QLoggerEngine::getLogger("map");
}


Maps::Maps(QWidget *parent)
    : QWidget(parent)
{
    setupUI();
}

void Maps::setupUI()
{
    QVBoxLayout *layout = new QVBoxLayout( this );

    //
    // Embedded webpage
    //
    mView = new QWebView( this );
    mView->settings()->setAttribute( QWebSettings::JavascriptEnabled, true );
    QString fileName = qApp->applicationDirPath() + "/gmap/map.html";
    if( !QFile(fileName).exists() ) {
        qDebug() << "File not found:" << fileName;
    }

    QUrl url = QUrl::fromLocalFile(fileName) ;
    mView->load( url );

    layout->addWidget( mView );
}
QAbstractItemModel* Maps::model() const
{
    return model_;
}

void Maps::setModel(QAbstractItemModel* model)
{
    model_ = model;
}


void Maps::goHome()
{
    mView->page()->mainFrame()->evaluateJavaScript( "map.panTo(myLatlng);" );
}

void Maps::addMarker(double x, double y, const QString& txt)
{
    mView->page()->mainFrame()->evaluateJavaScript(QString("addMarker(%1,%2,\"%3\");").arg(x).arg(y).arg(txt));
}

void Maps::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
    Q_UNUSED(previous);

    if(!model_)
        return;
    current_ = current;
    if(!current_.isValid())
        {
            logError(l)<<QStringLiteral("Невалидный индекс.");
            return;
        }

    updateCurrent();
}

void Maps::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles)
{
    if( (!topLeft.isValid()) || (!bottomRight.isValid()))
        return;
    if(! roles.contains(Qt::DisplayRole))
        return;
    for(int i = topLeft.row(); i < bottomRight.row(); ++i)
        {
            current_ = model_->index(i,0);
            updateCurrent();
        }
}

void Maps::onMapLoaded(bool ok)
{
    if(ok)
        {
//            if(current_name_.size())
//                {
//                    QString coord = current_link_.mid(current_link_.indexOf("=")+1);
//                    mView->page()->mainFrame()->evaluateJavaScript(QString("updateMarker(\"%1\",%2);").arg(current_name_).arg(coord));
//                }
        }
}

void Maps::updateCurrent()
{
    int row  = current_.row();
    current_link_ = current_.data(DM_LAST_POS_ROLE).toString().remove(QChar(0x0d));
    current_name_ = model_->data(model_->index(row,DM_NAME_IDX)).toString();
    QString coord = current_link_.mid(current_link_.indexOf("=")+1);
    try
    {
        mView->page()->mainFrame()->evaluateJavaScript(QString("updateMarker(\"%1\",%2);").arg(current_name_).arg(coord));
    }
    catch(std::exception & e)
    {
        logCritical(l)<<e.what();
    }
}

